var $ = window.$;
var jade = require('jade');
var animate = require('../../../util/animate');
var event = require('../../../core/event');
var util = require('../../../util/index');
var uiUtil = require('../../../util/ui');
var config = require('../../../core/config');
var slide = require('../../../core/slide');
var frac = require('../../../util/frac');

var _inited = false;

/**
 * grid设定
 */

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		event.bind(event.events.key.up, 'grid_move', this);
		event.lock('key', 'grid_move');
		_inited = true;
	},

	setManager: function (ma) {
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(param.key == 27){
			this.hide();
			return event.result.stopAll;
		}
	},

	move: function () {
		var inputs = this.parent.find('input');
		var beat = new Array(3);
		beat[0] = +(inputs.eq(0).val() || '0');
		beat[1] = +(inputs.eq(1).val() || '0');
		beat[2] = +(inputs.eq(2).val() || '0');
		if(frac.compare(beat, [0, 0, 1]) == 0){
			return;
		}

		var notes = this.manager.getSelectNotes();
		for(var i=0;i<notes.length;i++){
			var note = notes[i];
			note.beat = frac.add(note.beat, beat);
			if(note.endbeat){
				note.endbeat = frac.add(note.endbeat, beat);
			}
		}
		event.trigger(event.events.note.change);
		event.trigger(event.events.grid.align, {selected: true});

	},

	show: function(param){
		this.param = param;
		var tmpl = jade.compileFile('./tmpl/grid/gridmove.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_grid_move');
		this.parent.on('click','.g_barhead i', function () {
			self.hide();
		});
		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'close'){
				self.hide();
			}else if(type == 'move'){
				self.move();
				self.hide();
			}
		});

		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent);
		event.trigger(event.events.global.blur);
	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbind(event.events.key.up, 'grid_move');
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;